<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *{
            margin: 0;
            padding: 0;
            position: relative;
        }
        span{
            color: #fff;
            display: none;
        }
        .w{
            color:#fff;
        }
        .header{
            height: 170px;
            width: 80%;
            margin: 5px 100px;
            background-color: aqua;
        }
        .banner{
            height: 400px;
            width: 80%;
            margin: 5px 100px;
            background-color: red;
        }
        .main{
            height: 700px;
            width: 80%;
            margin: 5px 100px;
            background-color: blue;
        }
        .sidebar{
            position: absolute;
            top: 200px;
            right: 50px;
            height: 100px;
            width: 40px;
            background-color: brown;
        }
    </style>
</head>
<body>
    <div class="sidebar">
        <span class="backTop">返回到顶部</span>
    </div>
    <div class="header w">
        header
    </div>
    <div class="banner w">
        banner
    </div>
    <div class="main w">
        main
    </div>
    <script>
        //1.获取元素
        var back = document.querySelector('.backTop');
        var header = document.querySelector('.header')
        var banner = document.querySelector('.banner');
        var main = document.querySelector('.main');
        var txt = document.querySelector('.backTop')
        var sidebar = document.querySelector('.sidebar')
        //2.给页面添加滚动事件，如果header被滚动到顶部的话 则显示“返回到顶部”文字
        //获取banner盒子距离页面顶部的距离
        var bannerTop = banner.offsetTop
        var sideTop = sidebar.offsetTop - bannerTop //sidebar在页面滚动时应该固定停留的位置
        document.addEventListener('scroll',function(){
            //3.计算网页头部被卷去多少，如果高度等于header的高度 则显示文字
            var pageY = window.pageYOffset
            if(pageY >= header.offsetHeight){
                txt.style.display = 'block'
                sidebar.style.position = 'fixed'
                //页面滚动 siderbar的位置不会跳动
                sidebar.style.top = sideTop + 'px'
            }else{
                txt.style.display = 'none'
                sidebar.style.position = 'absolute'
                sidebar.style.top = '300px'
            }
            //4.
        })
    </script>
</body>
</html>